package com.budwk.app.sqfwV2.component;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 商铺公共类
 */

@IocBean
@Slf4j
public class ShopsComponent {

    @Inject
    private SysUserService userService;
    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    /**
     * 新增参数校验
     * @param shopsBaseInfo 商铺信息
     */
    public void checkAddData(SqfwShopsBaseInfo shopsBaseInfo) {
        if (StringUtils.isEmpty(shopsBaseInfo.getPlaceName())) {
            throw new AppException("商铺名称不能为空！");
        }
        if (StringUtils.isEmpty(shopsBaseInfo.getAddress())) {
            throw new AppException("商铺地址不能为空！");
        }
        shopsBaseInfo.setPlaceName(shopsBaseInfo.getPlaceName().trim()).setAddress(shopsBaseInfo.getAddress().trim());
    }

    public void initUpdateAddress(List<SqfwShopsBaseInfo> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        CompletableFuture.runAsync(() -> initUpdateInfo(list), taskQueryExecutor);
    }

    public static String buildDetailAddress(SqfwShopsBaseInfo shopsBaseInfo) {
        String detailAddress = shopsBaseInfo.getDetailAddress();
        String newDetailAddress = String.format("%s%s%s%s%s%s%s",
                StrUtil.formatStr(shopsBaseInfo.getProvince()),
                StrUtil.formatStr(shopsBaseInfo.getCity()),
                StrUtil.formatStr(shopsBaseInfo.getDistrict()),
                StrUtil.formatStr(shopsBaseInfo.getCounty()),
                StrUtil.formatStr(shopsBaseInfo.getCommunity()),
                StringUtils.isNotEmpty(shopsBaseInfo.getActualAddress()) ? shopsBaseInfo.getActualAddress() : shopsBaseInfo.getAddress(),
                StrUtil.formatStr(shopsBaseInfo.getPlaceName()));
        if (StringUtils.isEmpty(detailAddress)) {
            shopsBaseInfo.setDetailAddress(newDetailAddress);
            return newDetailAddress;
        }
        if (StringUtils.isNotEmpty(detailAddress) && !newDetailAddress.equals(detailAddress)) {
            shopsBaseInfo.setDetailAddress(newDetailAddress);
            return newDetailAddress;
        }
        return null;
    }

    private static void initUpdateInfo(List<SqfwShopsBaseInfo> list) {
        ShopsBaseInfoService shopsBaseInfoService = NutzIocUtils.getBean(ShopsBaseInfoService.class);
        for (SqfwShopsBaseInfo shopsBaseInfo : list) {
            boolean isUpdate = false;
            String detailAddress = buildDetailAddress(shopsBaseInfo);
            if (StringUtils.isNotEmpty(detailAddress)) {
                isUpdate = true;
            }
            // 修改bus
            if (StringUtils.isEmpty(shopsBaseInfo.getBusinessParam())) {
                if (buildBusinessParam(shopsBaseInfo)) {
                    isUpdate = true;
                }
            }
            if (isUpdate) {
                shopsBaseInfoService.updateIgnoreNull(shopsBaseInfo);
            }
        }
    }

    private static boolean buildBusinessParam(SqfwShopsBaseInfo shopsBaseInfo) {
        SqfwFormsummaryNewService summarySafetyService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        where.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, shopsBaseInfo.getId());
        cnd.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        cnd.limit(1);
        Sqfw_formSummary_new summaryNew = summarySafetyService.fetch(cnd);
        if (summaryNew != null ) {
            if (summaryNew.getType().equals(SupportBusinessTypeEnum.SAFETY_CHECK.getName())) {
                if (summaryNew.getCounty().equals("大营路街道")) {
                    String s = cleanDayYingRoad(summaryNew);
                    shopsBaseInfo.setBusinessParam(s);
                    return true;
                }
            }
        }
        return false;
    }

    private static String cleanDayYingRoad(Sqfw_formSummary_new summaryNew) {
        FireSafetyOnDayingRoadPdfDTO f = JSONObject.parseObject(summaryNew.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
        String mainBusinessScope = f.getMainBusinessScope();
        String industrySector = f.getIndustrySector();
        List<JSONObject> list = new ArrayList<>();
        JSONObject p = new JSONObject();
        p.put("businessType", SupportBusinessTypeEnum.SAFETY_CHECK.getName());
        p.put("code", SupportBusinessTypeEnum.SAFETY_CHECK.getCode());
        if (StringUtils.isNotEmpty(mainBusinessScope)) {
            String dictName = DictComponent.getDictName(mainBusinessScope, null);
            // 查詢不到字典数据 后期需要补全信息
            if (StringUtils.isNotEmpty(dictName)) {
                List<JSONObject> tags = new ArrayList<>();
                JSONObject p1 = new JSONObject();
                p1.put("businessType", "主要经营范围");
                p1.put("key", mainBusinessScope);
                p1.put("name", dictName);
                if (StringUtils.isNotEmpty(industrySector)) {
                    Map<String, String> map = DictComponent.INDUSTY_SECTOR_TYPES_MAP();
                    List<JSONObject> industrySectors = new ArrayList<>();
                    JSONObject p2 = new JSONObject();
                    p2.put("businessType", "行业领域");
                    p2.put("key", industrySector);
                    p2.put("name", map.get(industrySector));
                    industrySectors.add(p2);
                    p1.put("tag", industrySectors);
                }
                tags.add(p1);
                p.put("tag", tags);
            }

        }
        list.add(p);
        return JSONObject.toJSONString(list);

    }

    /***
     * 构建标签
     * @param param 前端参数
     * @param shopsBaseInfo 数据库原数据
     */
    public void buildLable(SqfwShopsBaseInfo param, SqfwShopsBaseInfo shopsBaseInfo) {
        // 1 构建type标签
        // 2 构建businessParam标签
        if (StringUtils.isEmpty(shopsBaseInfo.getBusinessParam())) {
            return;
        }
        if (StringUtils.isEmpty(param.getBusinessParam())) {
            return;
        }
        List<PersonnelTagDTO> lists = JSONArray.parseArray(shopsBaseInfo.getBusinessParam(), PersonnelTagDTO.class);
        // 先删除原有标签
        lists.removeIf(e -> e.getCode().equals(param.getServiceType()));
        List<PersonnelTagDTO> paramList = JSONArray.parseArray(param.getBusinessParam(), PersonnelTagDTO.class);
        lists.addAll(paramList);
        String jsonString = JSONObject.toJSONString(lists);
        log.info("shop buildLable paramList res: {}", jsonString);
        param.setBusinessParam(jsonString);
    }

    public static void clearLabel(List<SqfwShopsBaseInfo> list, String type) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        if (StringUtils.isEmpty(type)) {
            return;
        }
        for (SqfwShopsBaseInfo s : list) {
            s.setType(type);
            SupportBusinessTypeEnum anEnum = SupportBusinessTypeEnum.getCodeByName(type);
            if (anEnum != null) {
                s.setServiceType(anEnum.getCode());
            }
            if (StringUtils.isEmpty(s.getBusinessParam())) {
                continue;
            }
            List<PersonnelTagDTO> lists = JSONArray.parseArray(s.getBusinessParam(), PersonnelTagDTO.class);
            List<PersonnelTagDTO> busList = lists.stream().filter(e -> e.getBusinessType().equals(type)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(busList)) {
                s.setBusinessParam(JSONObject.toJSONString(busList));
            }
        }
    }
}
